import base64
import json

from locust import FastHttpUser, task, constant_pacing, run_single_user, between, events

index_cookie = 2000

def get_cookie():
    global index_cookie
    index_cookie += 1
    l = []
    with open('../cookie.txt', mode='r', encoding='utf8') as f:
        for account in f:
            l.append(account.strip())
        return str(l[index_cookie])

def enconde_bs64(data):
    data = json.dumps(data)
    encode64 = base64.b64encode(data.encode('utf-8'))
    return encode64.decode('utf-8')

def decode64_str(data):
    decode64 = base64.b64decode(data)
    decode64_str = decode64.decode('utf-8')
    return decode64_str


class OtherTask(FastHttpUser):
    host = "https://www.retone-hearing.fit"
    wait_time = between(1,3)
    header = {"Content-Type": "application/json"}
    abstract = True
    cookie = get_cookie()

    def on_start(self):
        numbers_of_user = False
        if numbers_of_user == True:
            self.header = {"Cookie": f"hearingaid_user={get_cookie()}",
                           "Content-Type": "application/json"}
        else:
            self.header = {"Cookie": f"hearingaid_user={self.cookie}",
                           "Content-Type": "application/json"}

    @task
    def firmware_upgrade(self):
        # 获取固件最新版本信息
        url = '/platformRetoneFit/api/needAppUserAuth/responseEncode/requestDecode/getFirmwareUpgradeVersion'

        data = {
            "deviceTypeCode": "1",
            "chipTypeCode": "1"
        }

        with self.rest('post', url, data=enconde_bs64(data), headers=self.header) as resp:
            if resp.status_code != 200 or (resp.js['data'] is None and resp.js['description'] is not None):
                resp.failure(f"=======错误返回:status_code={resp.status_code},resp={resp.text}==========")
            else:
                resp.success()

    @task
    def update_APP_plat(self):
        # 更新app用户平台特有信息
        url = '/platformRetoneFit/api/needAppUserAuth/responseEncode/requestDecode/updateAppUserPlatformSpecificInfo'
        data = {
            "deviceToken": "1e2c1dd38956233",
            "userPhoneType": "IOS",
            "speechRecognitionEnable": False
        }
        with self.rest('post', url, data=enconde_bs64(data), headers=self.header) as resp:
            if resp.status_code != 200 or (resp.js['data'] is None and resp.js['description'] is not None):
                resp.failure(f"=======错误返回:status_code={resp.status_code},resp={resp.text}==========")
            else:
                resp.success()

    @task
    def get_app_version(self):
        url = '/platformRetoneFit/api/needAppUserAuth/responseEncode/requestDecode/getAppVersionInfo'
        with self.rest('post', url, headers=self.header) as resp:
            if resp.status_code != 200 or (resp.js['data'] is None and resp.js['description'] is not None):
                resp.failure(f"=======错误返回:status_code={resp.status_code},resp={resp.text}==========")
            else:
                resp.success()


if __name__ == '__main__':
    run_single_user(OtherTask)